function $(s){
	return document.querySelectorAll(s);
}
var lis=$("#list li")
for(var i=0;i<lis.length;i++){
	lis[i].onclick=function(){
		for(var j=0;j<lis.length;j++){
			lis[j].className="";
		}
		this.className="selected"
		load("/media/"+this.title);
	}
}
//异步请求
var xhr=new XMLHttpRequest();
var ac=new (window.AudioContext||window.webkitAudioContext)();
var gianNode=ac[ac.createGain?"createGain":"createGainNode"]();
gianNode.connect(ac.destination);

//音频分析
var analyser=ac.createAnalyser();
var size=128;
analyser.fftSize=size*2;

analyser.connect(gianNode);

var source=null;
var count=0;

var box=$("#box")[0];
var height,width;
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
box.appendChild(canvas);
var Dots=[];

function random(m,n){
	return Math.round(Math.random()*(n-m)+m);
}
function getDots(){
	for(var i=0;i<size;i++){
		var x=random(0,width);
		var y=random(0,height);
		var color="rgb("+random(0,255)+","+random(0,255)+","+random(0,255);
		Dots.push({
			x:x,
			y:y,
			color:color
		})
	}
}
function resize(){
	height=box.clientHeight;
	width=box.clientWidth;
	canvas.height=height;
	canvas.width=width;
	var line=ctx.createLinearGradient(0,0,0,height);
	line.addColorStop(0,"red");
	line.addColorStop(0.5,"yellow");
	line.addColorStop(1,"green");
	ctx.fillStyle=line;
}
resize();
window.onresize=resize;
//条形图
function draw(arr){
	ctx.clearRect(0,0,width,height);
	var w=width/size;
  for(var i=0;i<size;i++){
  	var h=arr[i]/256*height;
  	ctx.fillRect(w*i,height-h,w*0.6,h);
  }
}
//选择播放外观
var types=$("#type li");
for(var i=0;i<types.length;i++){
	types[i].onclick=function(){
		for(var j=0;j<types.length;j++){
			types[j].className="";
		}
		this.className="selected";
	}
}
function load(url){
	var n=++count;
	source&&source[source.stop?"stop":"noteOff"]();
	xhr.abort();//终止上一步的请求
	xhr.open("GET",url);
	xhr.responseType="arraybuffer";
	xhr.onload=function(){
		if(n!=count)return;
		ac.decodeAudioData(xhr.response,function(buffer){
			if(n!=count)return;
			var bufferSource=ac.createBufferSource();
			bufferSource.buffer=buffer;
			bufferSource.connect(analyser);
			bufferSource[bufferSource.start?"start":"noteOn"](0);
			source=bufferSource;

		},function(err){
			console.log(err)
		})
	}
	xhr.send();
}
//得到分析数据
function visualizer(){
	var arr=new Uint8Array(analyser.frequencyBinCount);
	requestAnimationFrame=window.requestAnimationFrame||
	window.webkitRequestAnimationFrame;
	function v(){
		analyser.getByteFrequencyData(arr);
		requestAnimationFrame(v);
		draw(arr);
	}
	requestAnimationFrame(v);

}
visualizer();
//改变声音大小
function changeVolume(percent){
	gianNode.gain.value=percent*percent;
}
$("#volume")[0].onchange=function(){
	changeVolume(this.value/this.max);
}
$("#volume")[0].onchange();